import React,{useEffect, useRef, useState} from "react";
import {Tabs,Form,Select,Input,DatePicker,Button} from 'antd'
import LlxForm from 'components/LlxForm/index'

import commonConfig from "static/js/commonConfig";

import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'
import LlxTable from 'components/LlxTable'
import { getSongPool, getVideoPool, getLessonPool, getVideoAblumPool, getPullBook, getPullBookPool, getWordPool, getPaperPool, getStudyVideoPool, delPoolData} from 'api/index'
const {TabPane} = Tabs
const {Search} = Input

const { RangePicker } = DatePicker;
const {getColumns} = commonConfig

const taskList = [
  {value:'单词',key:'WORD',id:'601'},
  {value:'音频',key:'SONG',id:'602'},
  {value:'视频',key:'VIDEO',id:'603'},
  {value:'视频专辑',key:'ALBUM_VIDEO',id:'604'},
  {value:'学习视频',key:'LE_VIDEO',id:'608'},
  {value:'泛读书',key:'BOOK',id:'605'},
  {value:'精读书',key:'IR_BOOK',id:'606'},
  {value:'试卷',key:'PAPER',id:'607'},
  {value:'主题课',key:'LESSON',id:'609'}
]

function Test(props) {

const {dictionaries} = props
const [form] = Form.useForm()
const [loading,setLoading] = useState(false)
const [total,setTotal] = useState(false)
const [tabIndex,setTabIndex] = useState('601')
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
const [columns,setColumns] = useState([])

// 表单数据
const formItem = [
  {label: '状态', name: 'status', span: 3,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'dictValue',label:'dictValue'}}
    placeholder={'请选择状态'}
    options={dictionaries.wordStatus}
  >
  </Select>
}},
{label: '创建人', name: 'createBy',  span: 3 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择创建人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '负责人', name: 'manager',  span: 4,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择负责人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '更新人', name: 'updateBy',  span: 4 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择更新人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '更新时间', name: 'updateTime', span: 5,render: () => {
  return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}},
{label: '', name: 'name' , span: 5,render: () => {
    return  <Search placeholder="请输入关键词搜索" onSearch={getNewList} enterButton />
} }
]
//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='areaPush/testPool')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='areaPush/testPool')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps

  // 1.切换tab
const callback = (key)  => {
    setTabIndex(key)
    setPagination({
      current:1,
      pageSize:20
    })
  }
// 1.1
  useEffect(()=>{
    getNewList()
  },[tabIndex]) // eslint-disable-line react-hooks/exhaustive-deps

  // 2.获取数据
  const getNewList = async(value) => {
    setLoading(true)
    // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]
    // 缓存数据
   const data = {
    pagination: value&&value.pageSize?value:pagination,
    form:form.getFieldValue(),
    tab:1
   }

   props.setPageDataFn('areaPush/testPool',data) 

   setColumns(getColumns(taskList.findIndex(i=>i.id===tabIndex)+1+'',goInfo,props.userInfo.userName))

   const params = {
    currPage:value&&value.pageSize?value.current:pagination.current,
    pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
    levelId: 255,
    poolId: tabIndex,
   }
  //  发送请求
  if (tabIndex === '601') {
    params.wordName = form.getFieldValue().name
    params.wordStatus = form.getFieldValue().status
    const res1 = await getWordPool(params)
    const data1= res1.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(data1)
    setTotal(res1.result.total)
  } else if (tabIndex === '602') {
    params.songName = form.getFieldValue().name
    params.songStatus = form.getFieldValue().status
    const res1 = await getSongPool(params)
    const data1= res1.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(data1)
    setTotal(res1.result.total)
  } else if (tabIndex === '603' || tabIndex === '604' || tabIndex === '608') {
    if (tabIndex === '604') {
      params.videoAblumName = form.getFieldValue().name
      params.albumVideoStatus = form.getFieldValue().status
      const res1 = await getVideoAblumPool(params)
      const data1= res1.result.records
      data1.forEach((i,j)=>{
        i.sort=j+1
      })
      setDataSource(data1)
      setTotal(res1.result.total)
    } else {
      params.videoName = form.getFieldValue().name
      params.videoStatus = form.getFieldValue().status
      if (tabIndex === '603') {
        const res1 = await getVideoPool(params)
        const data1= res1.result.records
        data1.forEach((i,j)=>{
          i.sort=j+1
        })
        setDataSource(data1)
        setTotal(res1.result.total)
      } else {
        const res1 = await getStudyVideoPool(params)
        const data1= res1.result.records
        data1.forEach((i,j)=>{
          i.sort=j+1
        })
        setDataSource(data1)
        setTotal(res1.result.total)
      }
    }
  } else if (tabIndex === '605' || tabIndex === '606') {
    params.bookName = form.getFieldValue().name
    params.bookStatus = form.getFieldValue().status
    if (tabIndex === '605') {
      const res1 = await getPullBook(params)
      const data1= res1.result.records
      data1.forEach((i,j)=>{
        i.sort=j+1
      })
      setDataSource(data1)
      setTotal(res1.result.total)
    } else {
      const res1 = await getPullBookPool(params)
      const data1= res1.result.records
      data1.forEach((i,j)=>{
        i.sort=j+1
      })
      setDataSource(data1)
      setTotal(res1.result.total)
    }
  } else if (tabIndex === '607') {
    params.paperName = form.getFieldValue().name
    params.paperStatus = form.getFieldValue().status
    const res1 = await getPaperPool(params)
    const data1= res1.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(data1)
    setTotal(res1.result.total)
  } else if (tabIndex === '609') {
    params.lessonName = form.getFieldValue().name
    params.lessonStatus = form.getFieldValue().status
    const res1 = await getLessonPool(params)
    const data1= res1.result.records
    data1.forEach((i,j)=>{
      i.sort=j+1
    })
    setDataSource(data1)
    setTotal(res1.result.total)
  }

  setLoading(false)

  }
  // 3.获取时间
   const getUpdateTime = (value,dataString) => {
    const data = form.getFieldValue()
    data.startTime=dataString[0]
    data.endTime=dataString[1]
    form.setFieldsValue(data)
   }

  //  4.去详情
  const goInfo = (a,b) => {
    console.log(a,b);

    switch(b) {
      case 'LESSON':
        props.history.push('/view/plan/themeSubjectInfo?id=' + a)
        props.addRouter({
          menuName:'主题课详情',url:'plan/themeSubjectInfo?id=' + a 
        })
      break
      case 'VIDEO':
        props.history.push('/view/video/videoInfo?id=' + a)
        props.addRouter({
          menuName:'视频详情',url:'video/videoInfo?id=' + a 
        })
      break
      case 'PAPER':
        props.history.push('/view/test/testPaperInfo?id=' + a)
        props.addRouter({
          menuName:'试卷详情',url:'test/testPaperInfo?id=' + a 
        })
      break
      case 'WORD':
        props.history.push('/view/word/wordInfo?id=' + a)
        props.addRouter({
          menuName:'单词详情',url:'word/wordInfo?id=' + a 
        })
      break
      case 'IR_BOOK':
        props.history.push('/view/book/intensiveBookInfo?id=' + a)
        props.addRouter({
          menuName:'精读书详情',url:'book/intensiveBookInfo?id=' + a 
        })
      break
      case 'BOOK':
        props.history.push('/view/book/bookInfo?id=' + a)
        props.addRouter({
          menuName:'泛读详情',url:'book/bookInfo?id=' + a 
        })
      break
      case 'ALBUM_VIDEO':
        props.history.push('/view/video/videoAlbumInfo?id=' + a)
        props.addRouter({
          menuName:'专辑详情',url:'video/videoAlbumInfo?id=' + a 
        })
      break
      case 'SONG':
        props.history.push('/view/audio/audioInfo?id=' + a)
        props.addRouter({
          menuName:'音频详情',url:'audio/audioInfo?id=' + a 
        })
      break
      case 'LE_VIDEO':
        props.history.push('/view/video/studyInfo?id=' + a)
        props.addRouter({
          menuName:'学习视频详情',url:'video/studyInfo?id=' + a 
        })
      break
      default:
        return
      }
  }
   return  <div  className="app-content animate__animated animate__fadeIn overflow">

    <LlxForm form={form} formItem={formItem}/>

    <div className="operate-btn">
     <div>
           <Button disabled={!selectedRowKeys.length} type='primary' className='animate__animated animate__fadeInLeft'>移除测试区</Button>
       </div>
    </div>

    <Tabs  activeKey={tabIndex} onChange={callback} className="app-content animate__animated animate__fadeIn">
      {
        taskList.map((i,j)=>{
          return  <TabPane tab={i.value} key={i.id}>
          <LlxTable
          loading={loading} 
          pagination={pagination}
          setPagination={setPagination}
          selectedRowShow={true}
          rowSelection={rowSelection.current}
          height={320}
          keyName={"sort"}
          total={total}
          getNewList={getNewList}
          columns={columns}
          dataSource={dataSource}/>
       </TabPane>
        })
      }
    </Tabs>
     </div>
}


// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(Test)
